
#include "User_Def.h"
#include "main.h"
#include "switch.h"
#include "py32f0xx.h"
#include "led.h"

SwitchGroup group1 = {
    .swBtn = {{.sw = SW1, .gpio = GPIOB, .index = 1}, {.sw = SW4, .gpio = GPIOF, .index = 4}},
    .pin = K1,
};

SwitchGroup group2 = {
    .swBtn = {{.sw = SW2, .gpio = GPIOB, .index = 2}, {.sw = SW3, .gpio = GPIOF, .index = 3}, {.sw = SW5, .gpio = GPIOF, .index = 5}, {.sw = SW6, .gpio = GPIOB, .index = 6}},
    .pin = K2,
};

u8 switch_active = 0;

void Switch_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOF_CLK_ENABLE();

    GPIO_InitStruct.Pin = group1.pin;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLDOWN;
    HAL_GPIO_WritePin(GPIOB, group1.pin, GPIO_PIN_RESET);
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = group2.pin;
    HAL_GPIO_WritePin(GPIOF, group2.pin, GPIO_PIN_RESET);
    HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);

    for (size_t i = 0; i < 2; i++)
    {
        GPIO_InitStruct.Pin = group1.swBtn[i].sw;
        GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
        HAL_GPIO_WritePin(group1.swBtn[i].gpio, group1.swBtn[i].sw, GPIO_PIN_SET);
        HAL_GPIO_Init(group1.swBtn[i].gpio, &GPIO_InitStruct);
    }

    for (size_t i = 0; i < 4; i++)
    {
        GPIO_InitStruct.Pin = group2.swBtn[i].sw;
        GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
        HAL_GPIO_WritePin(group2.swBtn[i].gpio, group2.swBtn[i].sw, GPIO_PIN_SET);
        HAL_GPIO_Init(group2.swBtn[i].gpio, &GPIO_InitStruct);
    }
}

void Switch_Watch(void)
{
    for (size_t i = 0; i < 2; i++)
    {
        HAL_GPIO_WritePin(group1.swBtn[i].gpio, group1.swBtn[i].sw, GPIO_PIN_RESET);
        /**
         * 延迟1ms，等 K1 状态变化。
         * 同时避免程序运行过快，导致后面的循环获取 HAL_GPIO_ReadPin(GPIOB, group1.pin) 为 RESET
         */
        HAL_Delay(1);
        if (HAL_GPIO_ReadPin(GPIOB, group1.pin) == GPIO_PIN_RESET)
        {
            // 按键按下
            switch_active = group1.swBtn[i].index;
        }
        else
        {
            if (switch_active == group1.swBtn[i].index)
            {
                switch_active = 0;
            }
        }
        HAL_GPIO_WritePin(group1.swBtn[i].gpio, group1.swBtn[i].sw, GPIO_PIN_SET);
    }
    for (size_t i = 0; i < 4; i++)
    {
        HAL_GPIO_WritePin(group2.swBtn[i].gpio, group2.swBtn[i].sw, GPIO_PIN_RESET);
        HAL_Delay(1);
        if (HAL_GPIO_ReadPin(GPIOF, group2.pin) == GPIO_PIN_RESET)
        {
            switch_active = group2.swBtn[i].index;
        }
        else
        {
            if (switch_active == group2.swBtn[i].index)
            {
                switch_active = 0;
            }
        }
        HAL_GPIO_WritePin(group2.swBtn[i].gpio, group2.swBtn[i].sw, GPIO_PIN_SET);
    }
}